package com.sunreal.paygateway.service.channel.wechat;

import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.github.binarywang.wxpay.bean.result.BaseWxPayResult;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.google.common.collect.Lists;

/**
 * 功能描述：检查微信返回结果是否成功，任何不成功就抛出WxPayException,需要catch住WxPayException,并处理
 *
 * @Author 彭广
 * @Date 2019/1/15
 */
@Slf4j
public class WxResultCheck {

    /**
     * 检查微信返回结果是否成功，任何不成功就抛出WxPayException,需要catch住WxPayException,并处理
     *
     * @param result 不返回
     * @throws com.github.binarywang.wxpay.exception.WxPayException 需要catch住WxPayException,并处理成返回格式
     */
    public static Map<String, Object> checkResult(BaseWxPayResult result) throws WxPayException {
        //校验结果是否成功
        List<String> successStrings = Lists.newArrayList(WxPayConstants.ResultCode.SUCCESS, "");
        if (!successStrings.contains(StringUtils.trimToEmpty(result.getReturnCode()).toUpperCase())
                || !successStrings.contains(StringUtils.trimToEmpty(result.getResultCode()).toUpperCase())) {
            StringBuilder errorMsg = new StringBuilder();
            WxPayException.Builder builder = WxPayException.newBuilder();
            if (result.getReturnCode() != null) {
                errorMsg.append("返回代码：").append(result.getReturnCode());
                builder.returnCode(result.getReturnCode());
            }
            if (result.getReturnMsg() != null) {
                errorMsg.append("，返回信息：").append(result.getReturnMsg());
                builder.returnMsg(result.getReturnMsg());
            }
            if (result.getResultCode() != null) {
                errorMsg.append("，结果代码：").append(result.getResultCode());
                builder.resultCode(result.getResultCode());
            }
            if (result.getErrCode() != null) {
                errorMsg.append("，错误代码：").append(result.getErrCode());
                builder.errCode(result.getResultCode());
            }
            if (result.getErrCodeDes() != null) {
                errorMsg.append("，错误详情：").append(result.getErrCodeDes());
                builder.errCodeDes(result.getErrCodeDes());
            }
            log.error("\n结果业务代码异常，返回结果：{},\n{}", result, errorMsg.toString());
            throw builder.build();
        }
        return JSON.parseObject(JSON.toJSONString(result));
    }
}
